package caozuoxitong;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PriorityScheduler {
    public PriorityScheduler() {
    }

    public static void prioritySchedule(List<PCB> processes) {
        List<PCB> finishList = new ArrayList();
        int currentTime = 0;

        while(!processes.isEmpty()) {
            PCB current = (PCB)processes.get(0);
            Iterator var4 = processes.iterator();

            while(var4.hasNext()) {
                PCB p = (PCB)var4.next();
                if (p.priority < current.priority) {
                    current = p;
                }
            }

            current.state = "运行";
            current.cpuTime = current.allTime;
            current.remainTime = 0;
            current.finishTime = currentTime + current.allTime;
            currentTime = current.finishTime;
            current.state = "结束";
            finishList.add(current);
            processes.remove(current);
        }

        printProcessInfo(finishList);
        printMetrics(finishList);
    }

    private static void printProcessInfo(List<PCB> processes) {
        System.out.println("进程ID\t优先级\t已用CPU时间\t总需时间\t结束时间\t状态");
        Iterator var1 = processes.iterator();

        while(var1.hasNext()) {
            PCB p = (PCB)var1.next();
            System.out.println(p.id + "\t\t" + p.priority + "\t\t" + p.cpuTime + "\t\t" + p.allTime + "\t\t" + p.finishTime + "\t\t" + p.state);
        }

    }

    private static void printMetrics(List<PCB> processes) {
        double totalTurnaroundTime = 0.0;

        double turnaroundTime;
        for(Iterator var3 = processes.iterator(); var3.hasNext(); totalTurnaroundTime += turnaroundTime) {
            PCB p = (PCB)var3.next();
            turnaroundTime = (double)p.finishTime;
        }

        double averageTurnaroundTime = totalTurnaroundTime / (double)processes.size();
        System.out.println("平均周转时间: " + averageTurnaroundTime);
    }
}
